package org.example.volunteerend.config;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * MyBatis配置类，添加JSON处理器
 */
@Configuration
public class TypeHandlerConfig {

    /**
     * 处理JSON数组到Java List的转换
     */
    @MappedTypes(List.class)
    public static class JsonListTypeHandler extends BaseTypeHandler<List<String>> {
        
        private static final ObjectMapper MAPPER = new ObjectMapper();
        
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
            try {
                ps.setString(i, MAPPER.writeValueAsString(parameter));
            } catch (JsonProcessingException e) {
                throw new SQLException("Error converting List to JSON: " + e.getMessage(), e);
            }
        }

        @Override
        public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
            return parseJson(rs.getString(columnName));
        }

        @Override
        public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            return parseJson(rs.getString(columnIndex));
        }

        @Override
        public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            return parseJson(cs.getString(columnIndex));
        }
        
        private List<String> parseJson(String json) {
            if (json == null || json.isEmpty()) {
                return new ArrayList<>();
            }
            
            try {
                return Arrays.asList(MAPPER.readValue(json, String[].class));
            } catch (JsonProcessingException e) {
                // 日志记录错误，但返回空列表避免应用崩溃
                System.err.println("Error parsing JSON to List: " + e.getMessage());
                return new ArrayList<>();
            }
        }
    }
} 